<template>
  <div class="dashboard-container">
    <div class="app-container">
      <!-- 靠右的按钮 -->
      <page-tools>
        <el-button type="primary" size="small" @click="openDialog('0')"
          >添加权限</el-button
        >
      </page-tools>
      <br />
      <!-- 表格 -->
      <!-- 树形表格：要加row-key值为每行数据唯一的字段；加上tree-props 表示展示的规则 -->
      <el-table
        row-key="id"
        border
        :data="list"
        :tree-props="{ children: 'child' }"
      >
        <el-table-column prop="name" align="center" label="名称" />
        <el-table-column prop="code" align="center" label="标识" />
        <el-table-column prop="description" align="center" label="描述" />
        <el-table-column align="center" label="操作">
          <template slot-scope="{ row }">
            <el-button type="text" @click="openDialog(row.id)">添加</el-button>
            <el-button type="text" @click="editRow(row.id)">编辑</el-button>
            <el-button type="text" @click="delRow(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- !添加修改 -->
    <addPerm ref="addPerm" @updateList="initData" />
  </div>
</template>
<script>
import {
  delPermission,
  getPermissionDetail,
  getPermissionList,
} from "@/api/permission";
import { tranListToTreeData } from "@/utils";
import addPerm from "./components/addPerm.vue";
export default {
  name: "Permission",
  components: { addPerm },
  data() {
    return {
      list: [],
    };
  },
  created() {
    this.initData();
  },
  methods: {
    // 获取所有权限
    async initData() {
      let res = await getPermissionList();
      this.list = tranListToTreeData(res, "0");
    },
    // 打开弹框
    openDialog(pid) {
      this.$refs.addPerm.formData.pid = pid;
      this.$refs.addPerm.dialogShow = true;
    },
    // 编辑回显
    async editRow(id) {
      // 1. 得到这行完整的数据
      let row = await getPermissionDetail(id);
      // 2. 赋给表单
      this.$refs.addPerm.formData = row;
      // 3. 弹框打开
      this.$refs.addPerm.dialogShow = true;
    },
    // 删除事件
    async delRow(id) {
      // 1. 确认框
      try {
        await this.$confirm("确认删除吗");
      } catch (error) {
        return console.log(error);
      }
      // 2. 发生删除请求
      await delPermission(id);
      // 3. 提示成功
      this.$message.success("删除成功");
      // 4. 更新列表
      this.initData();
    },
  },
};
</script>
<style lang="scss" scoped></style>
